package cn.schtwz.baselib.adapter;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.databinding.DataBindingUtil;
import androidx.databinding.ViewDataBinding;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import org.jetbrains.annotations.NotNull;

import java.util.List;

public abstract class BaseDataBingdingQuickAdapter<T, DB extends ViewDataBinding> extends BaseQuickAdapter<T, BaseViewHolder> {
    public BaseDataBingdingQuickAdapter(int layoutResId) {
        super(layoutResId);
    }

    @NotNull
    @Override
    public BaseViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        if (viewType != LOADING_VIEW && viewType != HEADER_VIEW && viewType != EMPTY_VIEW && viewType != FOOTER_VIEW) {
            DB binding = DataBindingUtil.inflate(LayoutInflater.from(parent.getContext()), mLayoutResId, parent, false);
            BaseViewHolder baseViewHolder = createBaseViewHolder(binding.getRoot());
            bindViewClickListener(baseViewHolder);
            return baseViewHolder;
        } else {
            return super.onCreateViewHolder(parent, viewType);
        }
    }

    @Override
    protected void convert(BaseViewHolder helper, T item) {
        DB binding = DataBindingUtil.getBinding(helper.itemView);
        onBindItem(binding, item);
    }

    protected abstract void onBindItem(DB binding, T item);


    private void bindViewClickListener(final BaseViewHolder baseViewHolder) {
        if (baseViewHolder == null) {
            return;
        }
        final View view = baseViewHolder.itemView;
        if (view == null) {
            return;
        }
        if (getOnItemClickListener() != null) {
            view.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    getOnItemClickListener().onItemClick(BaseDataBingdingQuickAdapter.this, v, baseViewHolder.getLayoutPosition() - getHeaderLayoutCount());
                }
            });
        }
        if (getOnItemLongClickListener() != null) {
            view.setOnLongClickListener(new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View v) {
                    return getOnItemLongClickListener().onItemLongClick(BaseDataBingdingQuickAdapter.this, v, baseViewHolder.getLayoutPosition() - getHeaderLayoutCount());
                }
            });
        }
    }

    @Override
    public void addData(@NonNull T data) {
        super.addData(data);
    }

    //分页参数
    public void addPageData(@NonNull List<T> data, int page) {
        if (data.isEmpty()) {
            loadMoreEnd(true);
        }
        if (page == 1) {
            setNewData(data);
        } else {
            addData(data);
            loadMoreComplete();//数据加载完毕
        }
    }
}
